package com.zjf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjf.entity.Cart;
import com.zjf.entity.OrderDetailet;
import com.zjf.entity.Orders;
import com.zjf.mapper.CartMapper;
import com.zjf.mapper.OrderDetailetMapper;
import com.zjf.mapper.OrdersMapper;
import com.zjf.service.IBusinessService;
import com.zjf.service.IOrdersService;
import com.zjf.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Resource
    private CartMapper cartMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private OrderDetailetMapper orderDetailetMapper;
    @Autowired
    IBusinessService businessService;

    @Override
    @Transactional
    public int createOrders(Orders orders) {
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart> cartList = cartMapper.listCart(cart.getUserId(),cart.getBusinessId());

        orders.setOrderDate(CommonUtil.getCurrentDate());
        orders.setOrderState(0);
        ordersMapper.saveOrders(orders);
        int orderId=orders.getOrderId();
        List<OrderDetailet> list = new ArrayList<>();
        for(Cart c : cartList) {
            OrderDetailet od = new OrderDetailet();
            od.setOrderId(orderId);
            od.setFoodId(c.getFoodId());
            od.setQuantity(c.getQuantity());
            list.add(od);
        }
        orderDetailetMapper.saveOrderDetailetBatch(list);
        List<OrderDetailet> listDetailet=orderDetailetMapper.listOrderDetailetByOrderId(orderId);
        orders.setList(listDetailet);
        orders.setBusiness(businessService.getBusinessById(orders.getBusinessId()));
        System.out.println("listDetailet+++=="+listDetailet);
        System.out.println("order+++==="+orders);

        cartMapper.removeCart(cart);

        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId){
        return ordersMapper.listOrdersByUserId(userId);
    }

    @Override
    public int payOrder(Integer orderId) {
        return ordersMapper.payOrder(orderId);
    }
}
